
import {Component} from '@angular/core';
import { NavController } from 'ionic-angular';
import {HttpService} from "../../providers/HttpService";
import {GlobalData} from "../../providers/GlobalData";
import {NativeServiceC} from "../../providers/NativeServiceC";

@Component({
  selector: 'page-home',  //sass名字
  templateUrl: 'home.html',  //路径
    providers: []
})
export class HomePage {

  //强制定义一个数组（必须有这三个属性，可以随意push需要的属性）
  channels:Array<{
    editable:boolean,
    id:number,
    name:string
  }>;
  editChannels = [];
  items = [];
  nextUrl:string = '';
  isRefresh:boolean = true;
  constructor(public navCtrl: NavController,
              private httpService:HttpService,
              private globalData:GlobalData,
              private nativeService:NativeServiceC,
 ) {

  }

  ionViewDidLoad() {
    this.getChannels();
  }

  changeChannel(channel:any,index:number){
    this.isRefresh = true;
    let url = '/v1/channels/' + channel.id + '/items';
    this.getItems(url);
  }

    // 加载更多
    doInfinite(event){
        this.getItems(this.nextUrl,{},event);
    }

    homeCellClick(index){
        console.log('cell组件通信',index);
    }

    homeLikeClick(index){
        console.log('cell组件通信',index);
    }

  private getChannels(){
    const channelUrl = '/v2/channels/preset';
    let sender={
      gender:1,
      generation:1
    }
    this.httpService.get(channelUrl,sender)
        .subscribe(res => {
          console.log(res);
          this.channels=res.channels;
          this.editChannels = res.candidates;
          let url='/v1/channels/'+this.channels[0].id+'/items';
          this.getItems(url);
        })
  }

  private getItems(url:string,sender?:Object,infiniteScroll?){
    sender = sender || {
          gender:1,
          generation: 1,
          limit:20,
          offset:0,
        };
        if(!this.isRefresh){
          this.globalData.showLoading=false;
        }
        this.httpService.get(url,sender).subscribe(res =>{
          console.log(res);
          this.nativeService.hideLoading();
          if(this.isRefresh) this.items.length=0;
          this.items=this.items.concat(res.items);
          this.nextUrl=res.paging.next_url;
          this.isRefresh = false;
          infiniteScroll && infiniteScroll.complete();
        })
  }

}
